package com.nibian.nibian.utils;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.text.TextUtils;
import android.util.DisplayMetrics;

import com.nibian.nibian.activity.MainActivity;

import java.util.Locale;

/**
 * Created by chenj on 2017/3/17.
 */

public class LanguagesUtils {

    //public static final String AUTO = "auto";
    //public static String autoLanguage = null;
    public static final String ZH = "zh";//中文
    public static final String EN = "en";//英文

    public static void checkLanguage(Context context){
        String showLan = null;
        String LAN = SharedPreferenceTools.getString(context,"LANGUAGES_KEY","");
//        if(TextUtils.equals(LAN,AUTO)){
//            Locale locale = Locale.getDefault();
//            String language = locale.getLanguage();
//            if(!TextUtils.isEmpty(language) && !TextUtils.equals(autoLanguage,language)) {
//                autoLanguage = language;
//                showLan = language;
//            }else {
//                showLan = null;
//            }
//        }else {
            Locale locale = Locale.getDefault();
            String language = locale.getLanguage();
            if(!TextUtils.equals(language,LAN)){
                showLan = LAN;
            }else{
                showLan = null;
            }
//        }
//
        if(!TextUtils.isEmpty(showLan)){
            showLanguage(context ,LAN);
            savaLanguage(context,LAN);
            freshView(context);//重新启动MainActivity
        }
    }

    public static void switchLanguage(Context context,String language){

        if(!TextUtils.isEmpty(language)){
            showLanguage(context,language);
            savaLanguage(context,language);
            freshView(context);//重新启动MainActivity
        }
    }

    public static  void showLanguage(Context context,String language) {
        Locale locale = Locale.getDefault();
        locale.setDefault(new Locale(language));
        //设置应用语言类型
        Resources resources = context.getResources();
        Configuration config = resources.getConfiguration();
        DisplayMetrics dm = resources.getDisplayMetrics();
        if (language.equals(ZH)) {
            config.locale = Locale.SIMPLIFIED_CHINESE;
        } else if(language.equals(EN)){
            config.locale = Locale.ENGLISH;
        }
        resources.updateConfiguration(config, dm);

    }

    public static void savaLanguage(Context context,String language){
        //保存设置语言的类型（这个里面我先保存一下，下面会讲到他的用处）
        SharedPreferenceTools.saveString(context,"LANGUAGES_KEY", language);
    }

    public static  void freshView(Context context){
        Intent intent = new Intent(context, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        context.startActivity(intent);

    }
}
